/*
 * 预付卡数据导入界面
 * panel中、下部分按钮尚未完成！
 * 中间table数据显示尚未完成！
 */



package view;

import interfacePack.ITableObserver;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import com.eltima.components.ui.DatePicker;

import dao.Excel03DAO;
import dao.Excel07DAO;
import dao.NewPayRecordDAO;
import exception.ViewException;

import model.PrepayRecordItem;
import model.PrepayTableModel;

public class PrePaymentDataAccessPanel extends JPanel implements ITableObserver{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private PrepayTableModel prepayTableModel = new PrepayTableModel();

	private JPanel topTextFieldPanel = new JPanel(new BorderLayout());
	private JPanel prepayDataCheckPanel = new JPanel(new BorderLayout());

	private JLabel addressLabel = new JLabel("文件地址: ");
	private JTextField prepayfiledir = new JTextField();
	private JButton chooseBn = new JButton("选择文件");
	private JButton uploadBn = new JButton("加载数据");
	private JTextField cardNoInser;
	private JButton delRecordBn, addRecordBn, serRecordBn;
	private JPanel rightTopTextFieldPanelBn = new JPanel(new FlowLayout(
			FlowLayout.RIGHT));

	JPanel prepayDataCheckUP;
	JLabel timedateLabel = new JLabel("日期时间：");
	JLabel cardnoLabel = new JLabel("卡号：");
	private JTable prepayRecordTable = new JTable();
	private JScrollPane scr;
	
	private ArrayList<PrepayRecordItem> all = new ArrayList<PrepayRecordItem>();

	private static final String DefaultFormat = "yyyy-MM-dd";

	public PrePaymentDataAccessPanel() {
		
		//observer订阅DAO
		Excel03DAO.register(this);
		Excel07DAO.register(this);
		
		setLayout(new BorderLayout());
		initTopTextFieldPanel();
		initPrepayDataCheckPanel();
		//在prepayDataCheckPanel中加一个查询Panel
		add(topTextFieldPanel, BorderLayout.NORTH);
		add(prepayDataCheckPanel, BorderLayout.CENTER);
	}

	private void initTopTextFieldPanel() {
		prepayfiledir.setForeground(Color.BLUE);
		chooseBn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				String dir = chooseFile();
				prepayfiledir.setText(dir);
			}

		});
		uploadBn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				try {
					JOptionPane.showMessageDialog(prepayfiledir, "点击确定开始加载数据，加载时间较长，请不要中途退出");
					uploadFile(prepayfiledir.getText());
					
				} catch (ViewException e) {
					JOptionPane.showMessageDialog(prepayfiledir, e.getMessage());
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(prepayfiledir, "文件路径不正确");
				}
			}

		});
		rightTopTextFieldPanelBn.add(chooseBn);
		rightTopTextFieldPanelBn.add(uploadBn);

		topTextFieldPanel.setBorder(new TitledBorder("导入预付卡历史数据"));
		topTextFieldPanel.add(prepayfiledir);
		topTextFieldPanel.add(addressLabel, BorderLayout.WEST);
		topTextFieldPanel.add(rightTopTextFieldPanelBn, BorderLayout.EAST);
	}

	private void initPrepayDataCheckPanel() {
		
		prepayDataCheckPanel.setBorder(BorderFactory
				.createTitledBorder("预付卡交易数据查询"));

		//设置预付卡交易数据查询panel顶部panel
		prepayDataCheckUP = new JPanel(new FlowLayout(FlowLayout.LEFT));
		// 设置时钟面板
		Date date = new Date();
		Font font = new Font("Times New Roman", Font.PLAIN, 13);
		Dimension dimension = new Dimension(140, 24);
		final DatePicker datepick = new DatePicker(date, DefaultFormat, font,
				dimension);
		datepick.setTimePanleVisible(true);
		System.out.println(datepick.getText());

		cardNoInser = new JTextField(14);
		//为搜索记录添加listener, 按日期查询
		serRecordBn = new JButton("搜索记录");
		serRecordBn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				String date = datepick.getText();
				String[] d = date.split("-");
				String datepara = "";
				for(int i = 0; i < d.length; i++) {
					datepara += d[i];
				}
				String cardID = cardNoInser.getText();
				ResultSet rs;
				try {
					rs = NewPayRecordDAO.getNewPayRecord(cardID, datepara);
					while(rs.next()) {
						PrepayRecordItem item = new PrepayRecordItem();
						item.setRow( rs.getString(1), rs.getString(2), 
								rs.getString(3), rs.getString(4), rs.getString(5));
						all.add(item);
					}
				}
				catch (ViewException e2) {
					e2.printStackTrace();
					JOptionPane.showMessageDialog(serRecordBn, e2.getMessage());
				}
				catch (SQLException e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(serRecordBn, "读取数据出错");
				}

				prepayTableModel.addAllRecords(all);
				prepayRecordTable.setModel(prepayTableModel);
				scr.repaint();
				all.clear();
			}		
		});

		prepayDataCheckUP.add(timedateLabel);
		prepayDataCheckUP.add(datepick);
		prepayDataCheckUP.add(cardnoLabel);
		prepayDataCheckUP.add(cardNoInser);
		prepayDataCheckUP.add(serRecordBn);
		
		prepayDataCheckPanel.add(prepayDataCheckUP, BorderLayout.NORTH);

		//设置预付卡交易数据查询panel中间交易记录列表

		prepayRecordTable.setSelectionBackground(Color.ORANGE);
		prepayRecordTable.setSelectionForeground(Color.blue);
		prepayRecordTable.setRowHeight(20);
		prepayRecordTable.setModel(prepayTableModel);
		scr = new JScrollPane(prepayRecordTable);
		prepayDataCheckPanel.add(scr, BorderLayout.CENTER);

		

		//设置预付卡交易数据查询panel底部按钮
		//to do：按钮功能尚未完成
//		JPanel prepayDataCheckDown = new JPanel(
//				new FlowLayout(FlowLayout.RIGHT));
//		delRecordBn = new JButton("删除记录");
//		delRecordBn.addActionListener(new ActionListener(){
//			public void actionPerformed(ActionEvent e) {
//				// TODO Auto-generated method stub				
//			}		
//		});
//		addRecordBn = new JButton("添加记录");
//		addRecordBn.addActionListener(new ActionListener(){
//			public void actionPerformed(ActionEvent e) {
//				// TODO Auto-generated method stub
//				JOptionPane.showMessageDialog(prepayDataCheckUP, "test");
//			}		
//		});
//
//		prepayDataCheckDown.add(addRecordBn);
//		prepayDataCheckDown.add(delRecordBn);
//		prepayDataCheckPanel.add(prepayDataCheckDown, BorderLayout.SOUTH);

	}


	// 选择文件.xlsx或.xls文件
	private String chooseFile() {
		String dir = "";
		Component parent = null; // Dialog上级组件
		JFileChooser chooser = new JFileChooser(".");

		javax.swing.filechooser.FileFilter dirFilter = new javax.swing.filechooser.FileFilter() {
			public boolean accept(File f) {
				if (f.getName().endsWith(".xlsx")
						|| f.getName().endsWith(".xls") || f.isDirectory()) {
					return true;
				}
				return false;
			}

			public String getDescription() {
				return "Excel文件（.xlsx或.xls）";
			}
		};

		chooser.setFileFilter(dirFilter);
		if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
			dir = chooser.getSelectedFile().getAbsolutePath();
		}

		return dir;
	}

	// todo::上传文件,dir是文件路径
	private void uploadFile(String dir) throws ViewException{

		
		ExcelAccess excelAccess = new ExcelAccess(dir);
		// 上传成功后需要更新table中的数据： prepayTableModel.addAllRecords((Collection)all);

	}

	public void update(ArrayList<String> cells) {
// todo::加载所有records到prepayRecordTable
		PrepayRecordItem item = new PrepayRecordItem();
		item.setRow(cells.get(0), cells.get(1), cells.get(2), cells.get(3), cells.get(4));
		all.add(item);
	}

	public void updateFinished() {
		prepayTableModel.addAllRecords(all);
		prepayRecordTable.setModel(prepayTableModel);
		scr.repaint();
		all.clear();
		JOptionPane.showMessageDialog(null, "数据加载完成");
	}
}
